<template>
	<view class="index home-bg">
		<view class="search-container">
			<!-- <navigator hover-class="none" @tap="goPage()">
                <image class="icon-md" src="/static/images/icon_news.png"> </image>
            </navigator> -->
			<navigator class="search-wrap" hover-class="none" url="/pages/goods/search">
				<u-search placeholder="请输入商品名称" wrap-bg-color="transparent" :bg-color="'#fff'" :disabled="true"
					:height="30"></u-search>
			</navigator>
			<!-- <view class="search-wrap">
                <u-search wrap-bg-color="transparent" :bg-color="'#fff'" :disabled="true" :height="30" @search="handleSearch" @custom="handleSearch"></u-search>
            </view> -->
		</view>
		<view class="contain">
			<view class="main">
				<!-- 轮播图 -->
				<!-- <swiper class="banner" circular :indicator-dots="true" :autoplay="true" :interval="3000"
					:duration="1000">
					<swiper-item v-for="(item, index) in bannerList" :key="index" @tap="goPage(item.imgName)">
						<image :src="item.imgUrl" mode="aspectFill"></image>
					</swiper-item>
				</swiper> -->
				<view class="goods">
					<view class="goods-title">
						<text class="line"></text>
						<view class="title-row">
							<uni-icons type="list" size="24" color="#ff4d4f"></uni-icons>
							<text class="bold xxl">重要通知</text>
						</view>
						<text class="line"></text>
					</view>

					<view class="article-content" style="height: 50px; margin: 0px 20px 0px 20px; padding-top: 5px;">
						<!-- <u-parse :content="this.lastImportantNotice"></u-parse> -->
						<u-notice-bar :text="lastImportantNotice" speed="100" fontSize="20"
							color="#000000"></u-notice-bar>
					</view>
				</view>

				<view class="goods">
					<view class="goods-title">
						<text class="line"></text>
						<view class="title-row">
							<uni-icons type="list" size="24" color="#ff4d4f"></uni-icons>
							<text class="bold xxl">通知公告</text>
						</view>
						<text class="line"></text>
					</view>
				</view>
				<view class="system-notice">
					<view>
						<!-- <u-text text="1" size="18px"></u-text> -->
					</view>
					<view>
						<navigator url="/pages/notice/index" hover-class="navigator-hover">
							<u-icon name="chat" size="26" label="更多"></u-icon>
						</navigator>
					</view>
				</view>
				<!-- <swiper class="swiper-box">
					<swiper-item class="swiper-item" @touchmove.stop>
						<scroll-view scroll-y style="height: 100%;width: 100%;" enable-back-to-top="true"
							@scrolltolower="reachBottom" :refresher-enabled="true" :refresher-triggered="refresherTriggered"
							@refresherrefresh="refresherrefresh"> -->
				<view style="height: 75px;">
					<view class="slot-card" v-for="(item, index) in noticeList.slice(0, 1)" :key="index"
						@click="redirectNoticeInfo(item.noticeId)">
						<u-row justify="space-between" gutter="10" customStyle="margin-bottom: 10px">
							<u-col span="9">
								<view style="color: black; font-weight: bold;"><b>{{ item.noticeTitle }}</b></view>
							</u-col>
							<u-col span="3">
								<u-tag v-if="item.noticeType == 1" text="系统通知" type="warning"
									style="padding-top: 10px;" />
								<u-tag v-if="item.noticeType == 2" text="系统公告" type="success"
									style="padding-top: 10px;" />
								<u-tag v-if="item.noticeType == 3" text="重要通知" type="error"
									style="padding-top: 10px;" />
							</u-col>
						</u-row>
						<u-row justify="space-between" customStyle="margin-bottom: 10px">
							<u-col span="9">
								<view style="color:darkblue;">{{ item.createTime }}</view>
							</u-col>
						</u-row>
					</view>
					<!-- <u-loadmore :status="loadStatus" bgColor="#f2f2f2"></u-loadmore> -->
				</view>
				<!-- </scroll-view>
					</swiper-item>
				</swiper> -->
				<!-- 公告 -->
				<!-- <view class="announcement-card">

					<u-text text="河南汉永集团是一家集玉米深加工、小麦深加工、单一饲料、粮食购销、热力开发、钢构设计加工、物流运输、商贸服务等产业为一体的综合性公司。" />

				</view> -->
				<!-- 分类标题 -->
				<view class="goods">
					<view class="goods-title">
						<text class="line"></text>
						<view class="title-row">
							<uni-icons type="list" size="24" color="#ff4d4f"></uni-icons>
							<text class="bold xxl">产品分类</text>
						</view>
						<text class="line"></text>
					</view>
				</view>
				<!-- 分类入口 -->
				<!-- <view class="nav" :style="'height:' + navSwiperH + 'rpx;'" v-if="navList.length">
                    <view class="nav-list">
                        <view class="nav-item" v-for="(item, index) in navList" :key="index" @tap="tapMenu(item)">
                            <image v-if="index===0" class="nav-item-icon" src="/static/images/酒精.png"></image>
							<image v-if="index===1" class="nav-item-icon" src="/static/images/农业.png"></image>
							<image v-if="index===2" class="nav-item-icon" src="/static/images/饲料.png"></image>
                            <view class="name">{{ item.commodityName }}</view>
                        </view>
                    </view>
                </view> -->
				<view class="order-list" v-for="(item, index) in productTypeList" :key="index">
					<view class="order-card" @tap="tapMenu(item)">
						<!-- 分类内容 -->
						<view class="order-content" style="salign-items: center;font-weight: bold;">
							<image class="goods-image" :src="item.pictureUrl" mode="aspectFill"
								@error="handleImageError" />
							<view class="order-details">
								<view class="account-info">
									
									<template v-if="parseRemark(item.remark)">
									  <view class="row-flex">
									    <view class="left-label">
									      {{ parseRemark(item.remark).title }}
									    </view>
									    <view class="right-list" style="text-align: center;">
									      <view v-for="(row, idx) in parseRemark(item.remark).list" :key="idx">
									        {{ row.name }}
									      </view>
									    </view>
									  </view>
									</template>
									<template v-else>
									  <text style="color:#999;">无数据</text>
									</template>
									
									<!-- 不适配 -->
									<!-- <div v-html="item.remark"></div> -->
									<!-- 不适配 -->
									<!-- <rich-text :nodes="item.remark"></rich-text> -->
									<!-- 不适配 -->
									<!-- <RichText :item="item" class="bank" /> -->
									<!-- 适配但没法换行 -->
									<!-- <u-parse :content="item.remark"></u-parse> -->
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 好物优选 -->
			<!-- <view class="goods" v-if="goodsList.length">
                <view class="goods-title">
                    <text class="line"></text>
                    <view class="title-row">
                        <image class="icon" src="/static/images/icon_new.svg"></image>
                        <text class="bold xxl">新品推荐</text>
                    </view>
                    <text class="line"></text>
                </view>
                <goods-list :list="goodsList"></goods-list>
                <loading-footer :status="status"></loading-footer>
            </view> -->

		</view>

		<u-back-top :scroll-top="scrollTop" :top="1000" :customStyle="{
            backgroundColor: '#FFF',
            color: '#000',
            boxShadow: '0px 3px 6px rgba(0, 0, 0, 0.1)'
        }"></u-back-top>
	</view>
</template>

<script>
	import GoodsList from '@/components/goods-list/goods-list.vue'
	import homeData from './home.json'
	import {
		getGoodsInfo,
		searchGoods,
		getImgInfo,
		getGoodsCategoryInfo,
	} from '@/api/goods/goods.js'
	import RichText from '@/components/RichText/RichText.vue';
	import {
		listAppnotice
	} from '@/api/system/appnotice.js'
	const trottle = (func, time = 1000, context) => {
		let previous = new Date(0).getTime();
		return function(...args) {
			let now = new Date().getTime();
			if (now - previous > time) {
				func.apply(context, args);
				previous = now;
			}
		};
	};
	export default {
		components: {
			GoodsList,
			RichText
		},
		data() {
			return {
				refresherTriggered: false,
				_refresherTriggered: false,
				scrollTop: 0,
				navSwiperH: 374,
				currentSwiper: 0,
				lastImportantNotice: '',
				page: 1,
				status: 'loading',
				navList: [],
				noticeList: [],
				goodsList: [],
				productTypeList: [],
				queryNoticeForm: {
					status: '0',
					pageNum: 1,
					pageSize: 10
				},
				loadStatus: '',
				queryFrom: {
					imgType: '1',
				},
				bannerList: [{
						image: 'https://henanhanyong1995.oss-cn-hangzhou.aliyuncs.com/WeChatUploadImg/leg1.jpg',
						url: '/pages/goods_list/goods_list?id=1'
					},
					{
						image: 'https://henanhanyong1995.oss-cn-hangzhou.aliyuncs.com/WeChatUploadImg/leg2.jpg',
						url: '/pages/goods_list/goods_list?id=2'
					},
					{
						image: 'https://henanhanyong1995.oss-cn-hangzhou.aliyuncs.com/WeChatUploadImg/leg3.jpg',
						url: '/pages/goods_list/goods_list?id=3'
					}
				],
				searchTimer: null, // 添加一个用于防抖的计时器变量
			}
		},
		async onLoad(options) {
			this.onPageScroll = trottle(this.onPageScroll, 500, this)
			// this.getNoticeList()
			this.getMenuFun();
			this.getBestListFun();
			this.searchImg();
			this.searchProdectType();
		},
		onShow() {
			this.getNoticeList()
			this.noticeList = []
		},
		onReachBottom() {
			this.getBestListFun()
		},

		onPullDownRefresh() {
			// this.getMenuFun()
		},
		onPageScroll(e) {
			const top = uni.upx2px(100)
			const {
				scrollTop
			} = e
			let percent = scrollTop / top
			this.navBg = percent > 1 ? 1 : percent
			this.scrollTop = scrollTop
		},
		methods: {
			formatRichText(html) {
				let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
					match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
					match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
					match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
					return match;
				});
				newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
					match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi,
						'max-width:100%;');
					return match;
				});
				newContent = newContent.replace(/<br[^>]*\/>/gi, '');
				newContent = newContent.replace(/\<img/gi,
					'<img style="max-width:100%;height:auto;display:inline-block;margin:10rpx auto;"');
				return newContent;
			},
			redirectNoticeInfo(noticeId) {
				this.$tab.navigateTo(`/pages/notice/item?noticeId=${noticeId}`)
			},
			refresherrefresh() {
				if (this._refresherTriggered) {
					return;
				}
				this._refresherTriggered = true;
				if (!this.refresherTriggered) {
					this.refresherTriggered = true;
				}
				this.loadStoreData();
			},
			reachBottom() {
				if (!this.loadNoticeList) {
					this.queryNoticeForm.pageNum += 1;
					this.getNoticeList();
				} else {
					this.loadStatus = "nomore"
				}
			},
			getNoticeList() {
				this.loadStatus = "loading"
				if (!this.loadNoticeList) {
					this.loadNoticeList = true;
				}
				listAppnotice(this.queryNoticeForm).then(res => {
					for (let i = 0; i < 2; i++) {
						this.noticeList.push(res.rows[i])
					}
					const importantNotices = res.rows.filter(item => item.noticeType == 3);
					console.log(importantNotices);
					if (importantNotices) {
						const data = importantNotices[0];
						console.log(data);
						this.lastImportantNotice = data.noticeContent;
					}
					/* if (res.rows.length == 10) {
						this.loadNoticeList = false
						this.loadStatus = "loadmore"
					} else {
						this.loadNoticeList = true
						this.loadStatus = "nomore"
					} */
				})
			},
			searchProdectType() {
				getGoodsCategoryInfo(this.queryFrom).then(res => {
					this.productTypeList = res.data
				})
			},
			searchImg() {
				getImgInfo(this.queryFrom).then(res => {
					this.bannerList = res.rows
				})
			},
			handleSearch(value) {
				// 清除之前的定时器
				if (this.searchTimer) {
					clearTimeout(this.searchTimer)
				}

				// 设置新的定时器，延迟500ms执行搜索
				this.searchTimer = setTimeout(() => {
					searchGoods({
						commodityName: value
					}).then(res => {
						this.goodsList = res.dataList
						console.log(res)
					}).catch(err => {
						uni.showToast({
							title: '搜索失败',
							icon: 'none'
						})
						console.log(err)
					})
				}, 500)
			},
			// 获取元素位置
			getRect(selector, all, context) {
				return new Promise(function(resolve) {
					let qurey = uni.createSelectorQuery();

					if (context) {
						qurey = uni.createSelectorQuery().in(context);
					}

					qurey[all ? "selectAll" : "select"](selector)
						.boundingClientRect(function(rect) {
							if (all && Array.isArray(rect) && rect.length) {
								resolve(rect);
							}
							if (!all && rect) {
								resolve(rect);
							}
						})
						.exec();
				});
			},
			// 获取好物优选
			async getBestListFun() {
				try {
					const {
						goodsInfo
					} = await getGoodsInfo()
					this.goodsList = goodsInfo.flat(1)
					this.goodsList = this.goodsList.map(v => {
						return {
							...v,
							count: 1
						}
					})
					this.status = 'end'
				} catch (error) {
					uni.showToast({
						title: '获取数据失败',
						icon: 'none'
					})
				}
				// let { page, goodsList, status } = this
				// if (status === 'finished') return false

				// const { code, data } = homeData.getBestList
				// uni.stopPullDownRefresh()

				// if (code === 1) {
				//     if (page === 1) goodsList = []
				//     const { dataList } = data
				//     goodsList.push(...dataList)
				//     page++

				//     // 更新状态
				//     if (goodsList.length <= 0) {
				//         status = 'empty'
				//     } else if (dataList.length < 10) { // 假设每页10条数据
				//         status = 'finished'
				//     }

				//     // 更新数据
				//     this.page = page
				//     this.goodsList = goodsList
				//     this.status = status
				// } else {
				//     this.status = 'error'
				// }
			},
			// 点击菜单
			tapMenu(item) {
				// 如果目标页面是 tabbar 页面
				uni.switchTab({
					url: '/pages/goods/index'
				});
				// 由于 switchTab 不能带参数，可以使用 vuex 或 本地存储来传递数据
				uni.setStorageSync('goodCategoryId', item.goodCategoryId);
			},
			// 跳转页面
			goPage(url) {
				uni.showToast({
					title: '暂未开通',
					icon: 'none'
				})
			},
			// 获取菜单
			getMenuFun() {
				getGoodsInfo().then(res => {
					const {
						goodsType
					} = res
					uni.stopPullDownRefresh()
					if (goodsType.length <= 5) {
						this.navSwiperH = 200
					} else {
						this.navSwiperH = 374
					}
					this.navList = goodsType
					// this.navList = res.goodsType.map(v => {
					//     return {
					//         ...v,
					//         name: v.commodityName,
					//     }
					// })
				})

				function arraySlice(data, array = [], optNum = 10) {
					data = JSON.parse(JSON.stringify(data));
					if (data.length <= optNum) {
						data.length > 0 && array.push(data);
						return array;
					}
					array.push(data.splice(0, optNum));
					return arraySlice(data, array, optNum);
				}
			},
			parseRemark(remark) {
			    try {
			      return JSON.parse(remark);
			    } catch (e) {
			      return null;
			    }
			}
		},
	}
</script>

<style lang="scss">
	page {
		background: url('https://henanhanyong1995.oss-cn-hangzhou.aliyuncs.com/WeChatUploadImg/login_bg.jpg') no-repeat center center;
		background-size: cover;
		background-repeat: no-repeat;
		background-size: 100% 100%; // 修改为100%宽度和高度
		background-attachment: fixed; // 固定背景不随内容滚动
		//min-height: 100vh;
		position: relative;
	}

	.slot-card {
		width: 710rpx;
		background-color: #ffffff;
		margin: 10rpx auto;
		box-sizing: border-box;
		padding: 1rpx 20rpx 1rpx 20rpx;
		font-size: 34rpx;
		color: $u-content-color;
	}

	.system-notice {
		padding: 0 20px 0 20px;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.index {
		.contain {
			.main {
				position: relative;
				z-index: 9;


				.banner {
					width: 100%;
					height: 360rpx;
					margin-bottom: 20rpx;

					overflow: hidden;

					image {
						width: 100%;
						height: 100%;
					}
				}



				.nav {
					position: relative;
					border-radius: 14rpx;
					background-color: #fff;
					padding: 20rpx 0;

					.nav-list {
						display: flex;
						flex-wrap: wrap;
						padding: 10rpx;

						.nav-item {
							width: 33.33%;
							display: flex;
							flex-direction: column;
							align-items: center;
							justify-content: center;
							padding: 16rpx 0;

							.nav-item-icon {
								width: 80rpx;
								height: 80rpx;
								margin-bottom: 12rpx;
								border-radius: 50%;
								background-color: #ffd8d8; // 图标背景色
							}

							.name {
								font-size: 24rpx;
								color: #333;
								text-align: center;
								width: 100%;
								padding: 0 10rpx;
								white-space: nowrap;
								overflow: hidden;
								text-overflow: ellipsis;
							}

							&:active {
								opacity: 0.8;
								transform: scale(0.95);
							}
						}
					}
				}

				.announcement-card {
					margin: 40rpx;
				}
			}

			.goods {
				.goods-title {
					height: 60rpx;
					display: flex;
					align-items: center;
					justify-content: center;

					.line {
						width: 58rpx;
						height: 1px;
						background-color: #ccc;
						margin: 0 22rpx;
					}

					.title-row {
						display: flex;
						align-items: center;
						justify-content: center;

						.icon {
							width: 38rpx;
							height: 38rpx;
							margin-right: 10rpx;
						}

						.bold {
							font-weight: bold;
						}

						.xxl {
							font-size: 36rpx;
						}
					}
				}
			}
		}
	}

	.order-list {
		padding: 2px 10px 2px 10px;
	}

	.order-item {
		margin-bottom: 10px;
	}

	.order-card {
		background: #fff;
		border-radius: 8px;
		overflow: hidden;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

		.order-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 12px;
			border-bottom: 1px solid #f5f5f5;

			.order-number {
				display: flex;
				align-items: center;
				gap: 8px;

				.label {
					color: #999;
					font-size: 13px;
					font-weight: 800;
				}

				.number {
					color: #333;
					font-size: 13px;
					font-weight: 500;
				}
			}
		}
		.goods-image image {
		  max-height: 100%;
		  display: inline-block; /* 确保vertical-align生效 */
		}

		.order-content {
			padding: 12px;
			display: flex;
			gap: 12px;
			align-items: center;

			.goods-image {
				width: 80px;
				height: 80px;
				border-radius: 4px;
				background: #f5f5f5;
				flex-shrink: 0;
				display: table-cell; /* 转为表格单元格 */
			    vertical-align: middle; /* 垂直居中 */
			}
			

			.order-details {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.customer-info {
					display: flex;
					justify-content: space-between;
					align-items: flex-start;

					.name {
						font-size: 15px;
						font-weight: 500;
						color: #333;
					}

					.time {
						font-size: 12px;
						color: #999;
					}
				}

				.account-info {
					margin-top: 8px;

					.bank {
						font-size: 18px;
						font-weight: bold;
						color: #666;
					}
				}
			}
		}

		&:active {
			background: #f9f9f9;
		}
	}
	.left-label {
		color: #F9AE3D;
		background: #fffbe6;         // 柔和的淡黄色背景
		min-width: 90px;
		text-align: center;
		font-size: 15px;
		font-weight: bold;
		border-radius: 6px;
		padding: 6px 16px;
		margin-right: 16px;          // 和右侧内容拉开距离
		box-shadow: 0 2px 8px rgba(249, 174, 61, 0.08); // 可选，增加立体感
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.search-container {
		flex: 1;
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		// background: url(../../static/images/bg_hometop.png) no-repeat;
		background-size: 100% auto;

		.icon-md {
			margin-left: 30rpx;
			--size: 44rpx;
			min-height: var(--size);
			min-width: var(--size);
			height: var(--size);
			width: var(--size);
			vertical-align: middle;
		}

		.search-wrap {
			margin-left: 20rpx;
			flex: 1;
			margin-right: 20rpx;
		}
	}

	.uni-card {
		margin: 0 !important;
		padding: 20rpx !important;
	}

	.card-actions {
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		align-items: center;
		height: 90rpx;
		border-top: 1px #eee solid;
	}

	.card-actions-item {
		display: flex;
		flex-direction: row;
		align-items: center;
	}

	.card-actions-item-text {
		font-size: 24rpx;
		color: #666;
		margin-left: 10rpx;
	}
</style>